//
//  HTPlayerManager.m
//  HeartTravel
//
//  Created by lanou on 15/10/29.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "HTPlayerManager.h"

@interface HTPlayerManager ()

// 用来保存音乐地址的数组
@property (nonatomic, strong) NSArray *musicArray;



@end
@implementation HTPlayerManager



- (instancetype)init{
    
    self = [super init];
    if (self) {
        _avPlayer = [[AVPlayer alloc] init];
    }
    return self;
}

// 单例
+ (instancetype)shareManager{
    
    static HTPlayerManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[HTPlayerManager alloc] init];
    });
    return manager;
}

// 播放地址的数组
// 给音乐播放器设置播放音乐的地址的数组
- (void)setManagerMusicArray:(NSArray *)array{
    
    _musicArray = array;
}

- (void)playWithIndex:(NSInteger)index{
    
    _playIndex = index;
    NSURL *musicURL = [NSURL URLWithString:_musicArray[index]];
    // 根据传过来的下标选择数组里响应的播放地址
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:musicURL];
    // 把播放器的播放地址替换为新的地址
    [_avPlayer replaceCurrentItemWithPlayerItem:item];
    [_avPlayer play];
}

// 下一首
- (void)nextMusic{
    
    _playIndex++;
    if (_playIndex == _musicArray.count) {
        _playIndex = 0;
    }
    // 判断如果是随机播放就随机一个播放下标
    if (_playType == PlayTypeRandom) {
        _playIndex = arc4random() % _musicArray.count;
    }
    [self playWithIndex:_playIndex];
}
// 上一首
- (void)beforeMusic{
    
    _playIndex--;
    if (_playIndex < 0) {
        _playIndex = _musicArray.count - 1;
    }
    // 判断如果是随机播放就随机一个播放下标
    if (_playType == PlayTypeRandom) {
        _playIndex = arc4random() % _musicArray.count;
    }
    [self playWithIndex:_playIndex];
}
// 播放/暂停
- (void)playAndPause{
    
    // AVPlayer当前的状态 0.0代表停止播放状态 1.0代表正在播放
    if (_avPlayer.rate == 0.0) {
        [_avPlayer play];
    } else {
        [_avPlayer pause];
    }
}
// 停止
- (void)stop{
    
    [self seekToTime:0];
    [_avPlayer pause];
}
// 跳转
- (void)seekToTime:(NSUInteger)time{
    
    CMTime newTime = _avPlayer.currentTime;
    // 秒 = value / 基数
    newTime.value = newTime.timescale * time;
    [_avPlayer seekToTime:newTime];
}

- (NSUInteger)finishTime{
    
    CMTime time = _avPlayer.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value / time.timescale;
}

- (NSUInteger)currentTime{
    
    CMTime time = _avPlayer.currentTime;
    return time.value / time.timescale;
}


@end
